<template>
	<view class="content">
		<z-paging ref="pagingRef" v-model="dataList" @query="queryList" :fixed="false">
			<view class="coupon-container" :class="{
				          'active-border': showRulePopup && currentRuleIndex === index,
				          'no-radius': showRulePopup && currentRuleIndex === index
				        }" v-for="(item, index) in dataList" :key="index">
				<view class="item">
					<view class="left">
						<view v-if="(item.usedAmount !== null && item.type === 1) || item.type === 3">
							<text class="unit">¥</text>
							<text class="money">{{item?.usedAmount}}</text>
						</view>
						<text v-if="item.type === 2 && item.discount !== null"
							class="price-text">{{item?.discount}}折</text>
						<text v-if="item.type === 2 || item.type === 3" class='text2'>无门槛</text>
						<text class="condition"
							v-if="item.type === 1 && item.withAmount !== null">满{{item?.withAmount}}可用</text>
					</view>
					<view class="right">
						<view class="desc-box">
							<text class="desc" v-if="item.title !== null">{{item?.title}}</text>
							<text class="date"
								v-if='item.serviceLife !== null'>有效期至{{item?.serviceLife.slice(0,10)}}</text>
							<view class="rule" @click.stop='showRule(item.useRule, index)'>使用规则
								<uni-icons type="right" size="12" color="#999999"></uni-icons>
							</view>
						</view>
						<view class="other-box" v-show="item.nearExpire === 1">
							<text class="expire">快过期</text>
						</view>
						<view class="use" @click='selectCoupon(item)'>去使用</view>

					</view>
					<!-- 上半圆点 -->
					<view class="coupon-dot coupon-dot-top"></view>
					<!-- 下半圆点 -->
					<view class="coupon-dot coupon-dot-bottom"></view>
				</view>

				<!-- 规则框 -->
				<view class="rules-box" v-if="showRulePopup && currentRuleIndex === index">
					{{currentRule}}
				</view>
			</view>

			<template #empty>
				<view class="empty-container">暂无可用优惠券</view>
			</template>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		getValidCouponList
	} from '@/api/coupon.js'
	import {
		getCityCode
	} from "@/common/util.js";
	import {
		onLoad
	} from "@dcloudio/uni-app";

	const dataList = ref([]);
	const pagingRef = ref(null);
	const usedCategory = ref('');
	// 定义变量存储接收的总价
	const totalPrice = ref(0);
	// 规则弹窗相关
	const showRulePopup = ref(false);
	const currentRule = ref("");
	const currentRuleIndex = ref(-1);

	onLoad((options) => {
		if (options.itemId) {
			usedCategory.value = options.itemId;
		}
		// 接收订单详情页传递的总价（转换为数字类型）
		if (options.totalPrice) {
			totalPrice.value = Number(options.totalPrice);
			console.log("接收的商品总价：", totalPrice.value); // 调试用
		}

		// 加载优惠券列表（此时可使用totalPrice判断优惠券是否适用）
		// setTimeout(() => {
		// 	pagingRef.value?.reload();
		// }, 50);
	});

	// 显示规则
	const showRule = (rule, index) => {
		if (showRulePopup.value && currentRuleIndex.value === index) {
			showRulePopup.value = false;
			currentRuleIndex.value = -1;
		} else {
			currentRule.value = rule;
			currentRuleIndex.value = index;
			showRulePopup.value = true;
		}
	};

	const selectCoupon = (coupon) => {
		// 方式1：全局事件传递（更可靠）
		uni.$emit('selectCoupon', coupon);
		// 方式2：保留页面栈传递（作为备选）
		const pages = getCurrentPages();
		const prevPage = pages[pages.length - 2];
		if (prevPage) {
			prevPage.$vm.$emit('selectCoupon', coupon);
		}
		uni.navigateBack(); // 返回上一页
	};

	// 列表数据请求
	const queryList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum: pageNum,
				pageSize,
				usedCity: getCityCode(),
				usedCategory: usedCategory.value,
				price: totalPrice.value
			};
			const res = await getValidCouponList(params);
			// 确保返回数据格式正确
			pagingRef.value?.complete(res.rows || []);
		} catch (error) {
			console.error("请求失败:", error);
			pagingRef.value?.complete(false);
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		height: 100vh;
		padding: 20rpx;
		background-color: #f5f5f5;
		box-sizing: border-box;
	}

	.empty-container {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.coupon-container {
		margin-bottom: 24rpx;
	}

	.active-border {
		.item {
			border: 1rpx solid #FF6A47;
			border-bottom: none;
		}

		.rules-box {
			border: 1rpx solid #FF6A47;
			border-top: none;
		}
	}

	.no-radius {
		.item {
			border-radius: 20rpx 20rpx 0 0 !important;
		}

		.rules-box {
			border-radius: 0 0 20rpx 20rpx !important;
		}
	}

	.item {
		position: relative;
		display: flex;
		height: 242rpx;
		margin-bottom: 0;
		border-radius: 20rpx;
		overflow: hidden;
		border: 1rpx solid transparent;
		transition: border-radius 0.2s ease;

		/* 默认模式 */
		&.normal-mode {
			.left {
				background: url("http://public.sxlingfu.com/moblie/images/coupon_left.png") 0 0/100% 100% no-repeat;
				color: white;
			}

			.right {
				background: url("http://public.sxlingfu.com/moblie/images/coupon_right.png") 0 0/100% 100% no-repeat;
			}
		}

		/* 灰色模式 */
		&.gray-mode {

			.left,
			.right {
				background: white !important;
				opacity: 0.6;
			}

			.left {
				color: #666 !important;
			}

			.desc,
			.date {
				color: #666 !important;
			}

			.use {
				background: #ddd !important;
			}
		}

		.left {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 30%;
			height: 100%;
			color: white;
			background: linear-gradient(135deg, #FFAB67, #FE5609);

			.price-text {
				font-size: 48rpx;
				font-weight: 600;
			}

			.unit {
				font-size: 36rpx;
				margin-right: 4rpx;
			}

			.money {
				font-size: 48rpx;
				font-weight: 600;
			}

			.condition {
				font-size: 24rpx;
				margin-top: 8rpx;
			}

			.text2 {
				font-size: 24rpx;
				margin-top: 8rpx;
			}
		}

		.right {
			position: relative;
			width: 70%;
			height: 100%;
			background-color: #fff;

			.desc-box {
				width: calc(100% - 180rpx);
				padding-left: 30rpx;
				height: 100%;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.desc {
					font-weight: 500;
					font-size: 32rpx;
					color: #333;
				}

				.date {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}

				.rule {
					display: flex;
					align-items: center;
					font-size: 22rpx;
					color: #999;
					margin-top: 14rpx;
				}
			}

			.other-box {
				position: absolute;
				top: 0;
				right: 0;

				.expire {
					background: #ffdfd8;
					border-radius: 0 20rpx 0 20rpx;
					padding: 4rpx 16rpx;
					font-size: 20rpx;
					color: #ff6a47;
					display: block;
				}
			}

			.use {
				position: absolute;
				top: 50%;
				right: 30rpx;
				transform: translateY(-50%);
				width: 120rpx;
				height: 50rpx;
				line-height: 50rpx;
				background: linear-gradient(90deg, #ffab67, #fe5609);
				border-radius: 25rpx;
				font-size: 24rpx;
				color: #fff;
				text-align: center;
			}

			.image-box {
				position: absolute;
				top: 50%;
				right: 30rpx;
				transform: translateY(-50%);

				image {
					width: 80rpx;
					height: 80rpx;
				}
			}
		}

		/* 圆点基础样式 */
		.coupon-dot {
			position: absolute;
			left: 30%;
			width: 16rpx;
			height: 8rpx;
			transform: translateX(-50%);
			z-index: 2;
			overflow: hidden;
			background-color: #f5f5f5;
		}

		/* 上半圆点 */
		.coupon-dot-top {
			top: -4rpx;
			width: 40rpx;
			height: 20rpx;
			border-top: none;
			border-radius: 0 0 20rpx 20rpx;
		}

		/* 下半圆点 */
		.coupon-dot-bottom {
			bottom: -4rpx;
			width: 40rpx;
			height: 20rpx;
			border-bottom: none;
			border-radius: 20rpx 20rpx 0 0;
		}
	}

	/* 规则框样式 */
	.rules-box {
		width: 100%;
		padding: 20rpx;
		background: #fff;
		border-top: none;
		border-radius: 0 0 20rpx 20rpx;
		color: #666;
		font-size: 24rpx;
		line-height: 36rpx;
		box-sizing: border-box;
	}
</style>